package com.myblog.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myblog.Utils.BeanCopyUtils;
import com.myblog.Utils.JwtUtil;
import com.myblog.Utils.RedisCache;
import com.myblog.domain.GlobalResponse;
import com.myblog.domain.Vo.BlogUserLoginVo;
import com.myblog.domain.Vo.UserInfoVo;
import com.myblog.domain.entity.LoginUser;
import com.myblog.domain.entity.User;
import com.myblog.mapper.UserMapper;
import com.myblog.services.LoginService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User>
        implements LoginService {
    @Resource
    private  AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Override
    public GlobalResponse Login(User user) {
        //	调用ProviderManager的方法进行认证 如果认证通过生成jwt
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //利用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(id.toString());
        //把用户信息存入Redis
        redisCache.setCacheObject("blogLogin:"+id,loginUser);
        //把token封装返回
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo=new BlogUserLoginVo(jwt,userInfoVo);
        return GlobalResponse.ok(blogUserLoginVo);
    }
}
